package cn.modoumama.common.tools.cipher;

import cn.modoumama.common.tools.StringUtils;
import cn.modoumama.common.tools.VerifyObject;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;

/**
 * 加密解密类<br>
 *
 * 创建人：邓强   <br>
 * 创建时间：2018/5/3/003 17:14    <br>
 * @version   V1.0
 */
public class Cipher {
  private String key = "MD5";

  public Cipher(){
    super();
  }

  public Cipher(String key) {
    this.key = key;
  }

  public static String byte2hex(byte[] b) {
    StringBuffer hs = new StringBuffer();
    String stmp = "";
    for (int n = 0; n < b.length; n++) {
      stmp = Integer.toHexString(b[n] & 0xFF);
      if (stmp.length() == 1)
        hs = hs.append("0").append(stmp);
      else {
        hs = hs.append(stmp);
      }
  }
    return hs.toString().toUpperCase();
  }

  public String encode(String input) {
    try {
      MessageDigest alga = MessageDigest.getInstance(key);
      alga.update(input.getBytes());
      return byte2hex(alga.digest());
    } catch (NoSuchAlgorithmException e) {
      //throw new SystemException("0000", e);
    }
    return input;
  }

  public String encode(String input,String charsetName) {
    try {
      MessageDigest alga = MessageDigest.getInstance(key);
      alga.update(input.getBytes(charsetName));
      return byte2hex(alga.digest());
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    }
    return input;
  }

  public String signature(Map<String, String> params, String secret) {
    if (VerifyObject.isEmpty(params) || StringUtils.isBlank(secret)) {
      return null;
    }
    TreeMap<String, String> treeMap = null;

    if(params instanceof TreeMap){
      treeMap = (TreeMap<String, String>)params;
    }else{
      treeMap = new TreeMap<>();
      treeMap.putAll(params);
    }

    String result = null;
    StringBuffer orgin = getBeforeSign(treeMap, secret);
    if (orgin == null)
      return result;

    return encode(orgin.toString(),"utf-8");
  }

  public static StringBuffer getBeforeSign(TreeMap<String, String> params, String secret) {
    StringBuffer orgin = new StringBuffer();
    if (params == null)
      return null;
    Map<String, String> treeMap = new TreeMap<String, String>();
    treeMap.putAll(params);
    Iterator<String> iter = treeMap.keySet().iterator();
    while (iter.hasNext()) {
      String name = iter.next();
      if(params.get(name) != null) {
        orgin.append(name).append(params.get(name));
      }
    }
    orgin.append(secret);
    return orgin;
  }
}